package com.kalvan.web.servlet.interceptor;

import com.kalvan.core.security.AESUtils;
import com.kalvan.core.security.RSAUtils;
import com.kalvan.web.servlet.annotation.ParamsDecrypted;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 解密请求参数
 *
 * @author chenliang
 */
public class DecryptInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ParamsDecrypted paramsDecrypted = null;
        if (handler instanceof HandlerMethod) {
            paramsDecrypted = ((HandlerMethod) handler).getMethod().getAnnotation(ParamsDecrypted.class);
        }
        //paramsDecrypted没标识注解默认为需要加解密
        if ((paramsDecrypted == null || paramsDecrypted.required())) {
            Map<String, String[]> parameterMap = request.getParameterMap();
            if (parameterMap.size() > 0) {
                for (Map.Entry<String, String[]> kv : parameterMap.entrySet()) {
                    //解密数据
                    String value = decryptParam(request.getHeader("key"), kv.getValue()[0]);
                    parameterMap.put(kv.getKey(), new String[]{value});
                }
            }
        }
        return super.preHandle(request, response, handler);
    }

    public static String decryptParam(String key, String param) {
        try {
            key = RSAUtils.decryptByPrivateKey(key);
        } catch (Exception e) {
            return null;
        }
        return AESUtils.decryptData(key, param);
    }
}

